package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.qu_tao.Item.NewsItem;
import com.example.qu_tao.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MianjiaShouyeFragment extends Fragment {
    // 顶部按钮
    private Button btnMyStore;
    private TextView btnBuy;
    private LinearLayout wodehuopinLayout;
    private LinearLayout caigouguanliLayout;
    private LinearLayout dingdanguanliLayout;
    private LinearLayout dianpuguanliLayout;
    private Button btnMoreNews;
    private List<NewsItem> newsList = new ArrayList<>();
    private static final String AUTHORITY = "com.example.qu_tao.provider";
    private static final Uri NEWS_URI = Uri.parse("content://" + AUTHORITY + "/news");

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fargment_maijiashouye, container, false);
        // 初始化视图
        initViews(view);
        // 设置点击监听
        setClickListeners();
        // 查询数据
        queryNewsData();
        // 填充新闻数据到视图
        fillNewsDataToViews(view);
        return view;
    }

    private void initViews(View view) {
        // 顶部按钮
        btnMyStore = view.findViewById(R.id.wodedianpu);
        btnBuy = view.findViewById(R.id.btnBuy);
        wodehuopinLayout = view.findViewById(R.id.wodehuopin);
        caigouguanliLayout = view.findViewById(R.id.caigouguanli);
        dingdanguanliLayout = view.findViewById(R.id.dingdanguanli);
        dianpuguanliLayout = view.findViewById(R.id.dianpuguanli);
        btnMoreNews = view.findViewById(R.id.btn_more_news);
    }

    private void setClickListeners() {
        // 顶部"我的店铺"按钮点击
        btnMyStore.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WodeDianpuActivity.class);
            startActivity(intent);
        });
        // 顶部"去买货"按钮点击 - 跳转回买家首页(ShouyeFragment)
        btnBuy.setOnClickListener(v -> {
            FragmentManager fragmentManager = getParentFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.fragment_content, new ShouyeFragment(), "ShouyeFragment");
            transaction.addToBackStack(null);
            transaction.commit();
            ((MainActivity) getActivity()).switchToSellerMode(false);
        });
        // 我的货品点击
        wodehuopinLayout.setOnClickListener(v -> {
            // 跳转到WodeHuopinActivity
            Intent intent = new Intent(getActivity(), WodeHuopinActivity.class);
            startActivity(intent);
        });
        caigouguanliLayout.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), CaigouGuanliActivity.class);
            startActivity(intent);
        });
        dingdanguanliLayout.setOnClickListener(v -> {
            // 跳转到DingDanActivity
            Intent intent = new Intent(getActivity(), DingDanActivity.class);
            startActivity(intent);
        });
        dianpuguanliLayout.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), DianpuGuanliActivity.class);
            startActivity(intent);
        });
        // "更多"按钮点击，跳转到新闻页面
        btnMoreNews.setOnClickListener(v -> {
            FragmentManager fragmentManager = getParentFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.fragment_content, new XinwenFragment(), "XinwenFragment");
            transaction.addToBackStack(null);
            transaction.commit();
        });
    }

    @SuppressLint("Range")
    private void queryNewsData() {
        ContentResolver contentResolver = getActivity().getContentResolver();
        // 新增查询字段：content和image_path
        String[] projection = {"title", "publish_time", "content", "image_path"};
        String sortOrder = "publish_time DESC LIMIT 2";
        Cursor cursor = contentResolver.query(NEWS_URI, projection, null, null, sortOrder);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndex("title"));
                String publishTime = cursor.getString(cursor.getColumnIndex("publish_time"));
                String content = cursor.getString(cursor.getColumnIndex("content"));
                String imagePath = cursor.getString(cursor.getColumnIndex("image_path"));
                // 更新NewsItem类，添加content和imagePath字段
                NewsItem newsItem = new NewsItem(title, publishTime);
                newsItem.setContent(content);
                newsItem.setImage_path(imagePath);
                newsList.add(newsItem);
            }
            cursor.close();
        }
    }

    // 填充新闻数据到视图
    private void fillNewsDataToViews(View view) {
        TextView title1 = view.findViewById(R.id.news_title1);
        TextView date1 = view.findViewById(R.id.news_date1);
        TextView title2 = view.findViewById(R.id.news_title2);
        TextView date2 = view.findViewById(R.id.news_date2);

        if (newsList.size() >= 1) {
            title1.setText(newsList.get(0).getTitle());
            date1.setText(newsList.get(0).getPublish_time());
            // 传递完整新闻项
            title1.setOnClickListener(v -> openNewsDetail(newsList.get(0)));
        }
        if (newsList.size() >= 2) {
            title2.setText(newsList.get(1).getTitle());
            date2.setText(newsList.get(1).getPublish_time());
            title2.setOnClickListener(v -> openNewsDetail(newsList.get(1)));
        }
    }

    private void openNewsDetail(NewsItem newsItem) {
        try {
            // 构建包含完整数据的JSON
            JSONObject newsData = new JSONObject();
            newsData.put("title", newsItem.getTitle());
            newsData.put("time", newsItem.getPublish_time());
            newsData.put("content", newsItem.getContent());
            newsData.put("image", newsItem.getImage_path());
            // 对JSON进行URL编码
            String encodedData = Uri.encode(newsData.toString(), "UTF-8");
            String url = "file:///android_asset/page/detail.html?news=" + encodedData;

            Intent intent = new Intent(requireContext(), WebViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
            // 错误处理：使用原始参数跳转作为备用方案
            String url = "file:///android_asset/page/detail.html?title=" + Uri.encode(newsItem.getTitle())
                    + "&time=" + Uri.encode(newsItem.getPublish_time());
            Intent intent = new Intent(requireContext(), WebViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
        }
    }
}